from django.shortcuts import render,render_to_response
from django.http import HttpResponseRedirect
from django import forms
from apps.login.models import User


# 定义表单模型
class UserForm(forms.Form):
    user_id = forms.CharField(label='ID :', max_length=50)
    password = forms.CharField(label='密码 :', widget=forms.PasswordInput())


# 登录
def login(request):
    if request.method == 'POST':
        uf = UserForm(request.POST)
        if uf.is_valid():
            # 获取表单用户密码
            user_id = uf.cleaned_data['user_id']
            password = uf.cleaned_data['password']
            # 获取的表单数据与数据库进行比较
            user = User.objects.filter(username__exact=user_id, password__exact=password)
            if user:
                return render_to_response('home.html', {'username': user_id})
            else:
                return HttpResponseRedirect('/login/')
    else:
        uf = UserForm()
    return render_to_response('login.html', {'uf': uf})

